package com.flyco.modules.stm.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.shiro.SecurityUtils;
import com.flyco.poi.excel.ExcelImportUtil;
import com.flyco.poi.excel.def.NormalExcelConstants;
import com.flyco.poi.excel.entity.ExportParams;
import com.flyco.poi.excel.entity.ImportParams;
import com.flyco.poi.excel.view.EntityExcelView;
import com.flyco.common.system.vo.LoginUser;
import com.flyco.common.api.vo.Result;
import com.flyco.common.system.query.QueryGenerator;
import com.flyco.common.util.oConvertUtils;
import com.flyco.modules.stm.entity.StmPrintContent;
import com.flyco.modules.stm.entity.StmPrintTemplate;
import com.flyco.modules.stm.vo.StmPrintTemplatePage;
import com.flyco.modules.stm.service.IStmPrintTemplateService;
import com.flyco.modules.stm.service.IStmPrintContentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.flyco.common.aspect.annotation.AutoLog;

/**
 * @Description: 打印模板
 * @Author: flyco
 * @Date: 2020-10-27
 * @Version: V1.0
 */
@Api(tags = "打印模板")
@RestController
@RequestMapping("/f/stm/stmPrintTemplate")
@Slf4j
public class StmPrintTemplateController {
    @Autowired
    private IStmPrintTemplateService stmPrintTemplateService;
    @Autowired
    private IStmPrintContentService stmPrintContentService;

    /**
     * 分页列表查询
     *
     * @param stmPrintTemplate
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "打印模板-分页列表查询")
    @ApiOperation(value = "打印模板-分页列表查询", notes = "打印模板-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(StmPrintTemplate stmPrintTemplate,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<StmPrintTemplate> queryWrapper = QueryGenerator.initQueryWrapper(stmPrintTemplate, req.getParameterMap());
        Page<StmPrintTemplate> page = new Page<StmPrintTemplate>(pageNo, pageSize);
        IPage<StmPrintTemplate> pageList = stmPrintTemplateService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param stmPrintTemplatePage
     * @return
     */
    @AutoLog(value = "打印模板-添加")
    @ApiOperation(value = "打印模板-添加", notes = "打印模板-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody StmPrintTemplatePage stmPrintTemplatePage) {
        StmPrintTemplate stmPrintTemplate = new StmPrintTemplate();
        BeanUtils.copyProperties(stmPrintTemplatePage, stmPrintTemplate);
        stmPrintTemplateService.save(stmPrintTemplate);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param stmPrintTemplatePage
     * @return
     */
    @AutoLog(value = "打印模板-编辑")
    @ApiOperation(value = "打印模板-", notes = "打印模板-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody StmPrintTemplatePage stmPrintTemplatePage) {
        StmPrintTemplate stmPrintTemplate = new StmPrintTemplate();
        BeanUtils.copyProperties(stmPrintTemplatePage, stmPrintTemplate);
        stmPrintTemplateService.updateById(stmPrintTemplate);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "打印模板-通过id删除")
    @ApiOperation(value = "打印模板-通过id删除", notes = "打印模板-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        stmPrintTemplateService.delMain(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "打印模板-批量删除")
    @ApiOperation(value = "打印模板-批量删除", notes = "打印模板-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.stmPrintTemplateService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "打印模板-通过id查询")
    @ApiOperation(value = "打印模板-通过id查询", notes = "打印模板-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        StmPrintTemplate stmPrintTemplate = stmPrintTemplateService.getById(id);
        return Result.ok(stmPrintTemplate);
    }


    /**
     * 通过code查询
     *
     * @param code
     * @return
     */
    @AutoLog(value = "打印模板-通过code查询")
    @ApiOperation(value = "打印模板-通过code查询", notes = "打印模板-通过code查询")
    @GetMapping(value = "/queryByCode")
    public Result<?> queryByCode(@RequestParam(name = "id", required = false) Long id, @RequestParam(name = "code", required = true) String code) {
        LambdaQueryWrapper<StmPrintTemplate> query = new LambdaQueryWrapper<StmPrintTemplate>();
        query.eq(StmPrintTemplate::getCode,code);
        if (oConvertUtils.isNotEmpty(id)) {
            query.ne(StmPrintTemplate::getId,id);
        }
        StmPrintTemplate stmPrintTemplate = stmPrintTemplateService.getOne(query,false);
        return Result.ok(stmPrintTemplate);
    }

    //===========================以下是子表信息操作相关API====================================

    /**
     * 通过主表id查询打印模板内容
     *
     * @param stmPrintContent
     * @return
     */
    @AutoLog(value = "打印模板内容-通过主表id查询")
    @ApiOperation(value = "打印模板内容-通过主表id查询", notes = "打印模板内容-通过主表id查询")
    @GetMapping(value = "/listStmPrintContentByMainId")
    public Result<?> listStmPrintContentByMainId(StmPrintContent stmPrintContent,
                                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                 HttpServletRequest req) {
        if (stmPrintContent.getTemplateCode() != null) {
            QueryWrapper<StmPrintContent> queryWrapper = QueryGenerator.initQueryWrapper(stmPrintContent, req.getParameterMap());
            Page<StmPrintContent> page = new Page<StmPrintContent>(pageNo, pageSize);
            IPage<StmPrintContent> pageList = stmPrintContentService.page(page, queryWrapper);
            return Result.ok(pageList);
        } else {
            return Result.error("请选择模板");
        }
    }

    /**
     * 添加打印模板内容
     *
     * @param stmPrintContent
     * @return
     */
    @AutoLog(value = "打印模板内容-添加")
    @ApiOperation(value = "打印模板内容-添加", notes = "打印模板内容-添加")
    @PostMapping(value = "/addStmPrintContent")
    public Result<?> addStmPrintContent(@RequestBody StmPrintContent stmPrintContent) {
        stmPrintContentService.save(stmPrintContent);
        return Result.ok("添加打印模板内容成功！");
    }

    /**
     * 编辑打印模板内容
     *
     * @param stmPrintContent
     * @return
     */
    @AutoLog(value = "打印模板内容-编辑")
    @ApiOperation(value = "打印模板内容-编辑", notes = "打印模板内容-编辑")
    @PutMapping("/editStmPrintContent")
    public Result<?> editStmPrintContent(@RequestBody StmPrintContent stmPrintContent) {
        stmPrintContentService.updateById(stmPrintContent);
        return Result.ok("编辑打印模板内容成功！");
    }

    /**
     * 通过id删除打印模板内容
     *
     * @param id
     * @return
     */
    @AutoLog(value = "打印模板内容-通过id删除")
    @ApiOperation(value = "打印模板内容-通过id删除", notes = "打印模板内容-通过id删除")
    @DeleteMapping(value = "/deleteStmPrintContent")
    public Result<?> deleteStmPrintContent(@RequestParam(name = "id", required = true) String id) {
        stmPrintContentService.removeById(id);
        return Result.ok("删除打印模板内容成功！");
    }

    /**
     * 批量删除打印模板内容
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "打印模板内容-批量删除")
    @ApiOperation(value = "打印模板内容-批量删除", notes = "打印模板内容-批量删除")
    @DeleteMapping(value = "/deleteBatchStmPrintContent")
    public Result<?> deleteBatchStmPrintContent(@RequestParam(name = "ids", required = true) String ids) {
        if (ids == null || "".equals(ids.trim())) {
            return Result.error("参数不识别！");
        }
        this.stmPrintContentService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");

    }


    /**
     * 导出excel
     *
     * @param request
     * @param stmPrintTemplate
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, StmPrintTemplate stmPrintTemplate) {
        // Step.1 组装查询条件
        QueryWrapper<StmPrintTemplate> queryWrapper = QueryGenerator.initQueryWrapper(stmPrintTemplate, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //Step.2 获取导出数据
        List<StmPrintTemplatePage> pageList = new ArrayList<StmPrintTemplatePage>();
        List<StmPrintTemplate> stmPrintTemplateList = stmPrintTemplateService.list(queryWrapper);
        for (StmPrintTemplate temp : stmPrintTemplateList) {
            StmPrintTemplatePage vo = new StmPrintTemplatePage();
            BeanUtils.copyProperties(temp, vo);
            List<StmPrintContent> stmPrintContentList = stmPrintContentService.selectByMainId(temp.getCode());
            vo.setStmPrintContentList(stmPrintContentList);
            pageList.add(vo);
        }
        //Step.3 调用AutoPoi导出Excel
        ModelAndView mv = new ModelAndView(new EntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "打印模板");
        mv.addObject(NormalExcelConstants.CLASS, StmPrintTemplatePage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("打印模板数据", "导出人:" + sysUser.getRealname(), "打印模板"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<StmPrintTemplatePage> list = ExcelImportUtil.importExcel(file.getInputStream(), StmPrintTemplatePage.class, params);
                for (StmPrintTemplatePage page : list) {
                    StmPrintTemplate po = new StmPrintTemplate();
                    BeanUtils.copyProperties(page, po);
                    stmPrintTemplateService.saveMain(po, page.getStmPrintContentList());
                }
                return Result.ok("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }
}
